﻿using System.Data;
using System;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.Collections.Generic;
using System.Linq;

namespace Geeno.API.Services
{
    using S = String;
    public abstract class CommonService
    {
        //protect ed const string CONNECTIONSTRING = "server=DESKTOP-SV537NV;database=Test;integrated security=true;";
        protected const S CONNECTIONSTRING = "Persist Security Info=False;User ID=test;Password=test@123456;Initial Catalog=DapperTest;Server=DESKTOP-0HNM5A8\\MSSQL2022;";
    }
    public static class DataBaseConfig
    {
        public static IDbConnection GetConnection(S connectionStringKey = "Sqlserver")
        {
            var m = AppConfig.GetConn(connectionStringKey);
            var conn = new SqlConnection(m);
            return conn;
        }
    }
    public class AppConfig
    {
        public static S GetConn(string connectStringKey = "Sqlserver")
        {
            var n = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
            return n.GetConnectionString(connectStringKey);
        }
    }
    public class ext
    {
        public static DataTable ListToTable<T>(List<T> list)
        {
            Type tp = typeof(T);
            //排除List类型
            var proInfos = tp.GetProperties().Where(x => !x.PropertyType.FullName.Contains("Generic"));
            DataTable dt = new DataTable();
            foreach (var item in proInfos)
            {
                dt.Columns.Add(item.Name, item.PropertyType);
            }
            foreach (var item in list)
            {
                DataRow dr = dt.NewRow();
                foreach (var proInfo in proInfos)
                {
                    object obj = proInfo.GetValue(item);
                    if (obj == null)
                        continue;
                    dr[proInfo.Name] = obj;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }

}
